#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <stdbool.h>
#include <sys/time.h>
#define MAX 5

int data[MAX];
int sum = 0, flag = 0;
pthread_mutex_t p_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t p_cond = PTHREAD_COND_INITIALIZER;

void * write_num(){
    for(int i = 0;i<MAX;i++)
    {
        pthread_mutex_lock(&p_mutex);
        while(flag)
        pthread_cond_wait(&p_cond,&p_mutex);
        for(int j = 0;j<MAX;j++){
            data[j] = rand()%10 +1;
        }
        flag = 1;
        pthread_mutex_unlock(&p_mutex);
        pthread_cond_signal(&p_cond);
    }
}

void * read_num(){
    for(int i = 0;i<MAX;i++)
    {
        pthread_mutex_lock(&p_mutex);
        while(!flag)
        pthread_cond_wait(&p_cond,&p_mutex);
        for(int j = 0;j<MAX;j++){
            sum += data[j];
        }
        printf("sum of array is: %d\n",sum);
        flag = 0;
        pthread_mutex_unlock(&p_mutex);
        pthread_cond_signal(&p_cond);
    }
}

int main(){
    struct timeval tv1,tv2;
    pthread_t thread0,thread1;
    gettimeofday(&tv1,NULL);
    pthread_create(&thread0, NULL, write_num, NULL);
    pthread_create(&thread1, NULL, read_num, NULL);
    pthread_join(thread0, NULL);
    pthread_join(thread1, NULL);
    gettimeofday(&tv2,NULL);
    printf("time cost is: %dus",tv2.tv_usec-tv1.tv_usec);
}